package com.schedualnew.mq.config;

import com.ewell.sdk.business.EwellServiceTool;
import com.ewell.sdk.business.EwellServiceTopicTool;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.web.client.RestTemplate;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

@Configuration
public class ApplicationConfig {

    @Bean
    public EwellServiceTool ewellServiceTool() {
        return new EwellServiceTool();

        // todo 测试
//        EwellServiceTool testMe = createTestedInstance(EwellServiceTool.class);
//        return testMe;
    }

    @SuppressWarnings("unchecked")
    private <T> T createTestedInstance(Class<T> clazz) {
        try {
            Field singleoneInstanceField = Unsafe.class.getDeclaredField("theUnsafe");
            singleoneInstanceField.setAccessible(true);
            Unsafe unsafe = (Unsafe) singleoneInstanceField.get(null);
            return (T) unsafe.allocateInstance(clazz);
        } catch (Exception e) {
            throw new RuntimeException("cannot instantiate " + clazz + " bypassing default constructor");
        }
    }

//    @Bean
//    public Jaxb2Marshaller getJaxb2Marshaller() {
//        Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
//        jaxb2Marshaller.setClassesToBeBound(ServiceConfig.class);
//        jaxb2Marshaller.setClassesToBeBound(ServiceConfigDefinition.class);
//        return jaxb2Marshaller;
//    }

    @Bean
    public Jaxb2Marshaller jaxb2Marshaller() {
        Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
        jaxb2Marshaller.setPackagesToScan("com.schedualnew.mq.yihuiesb.model");
        return jaxb2Marshaller;
    }

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        CookieStore cookieStore = new BasicCookieStore();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        HttpClient httpClient = HttpClientBuilder.create()
                .setDefaultCookieStore(cookieStore)
                .setRedirectStrategy(new LaxRedirectStrategy())
                .build();
        factory.setHttpClient(httpClient);

        restTemplate.setRequestFactory(factory);

        return restTemplate;
    }
}
